package com.company.cloud.common.bean;

import com.company.cloud.common.constant.BaseReturnEnum;
import com.company.cloud.common.exception.BusinessException;
import com.company.cloud.common.utils.CheckUtils;

import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
public class BaseClientResult<T> {

	private String code;

	private String msg;

	private T data;

	public BaseClientResult() {

	}
	
	public static <T> T getResultData(BaseClientResult<T> result) {
		return getResultData(result, null);
	}
	
	public static <T> T getResultData(BaseClientResult<T> result,T def) {
		if(CheckUtils.hasClientResult(result)) {
			return result.getData();
		}else {
			return def;
		}
	}
	
	public static <T> T getResultData2Error(BaseClientResult<T> result,T def)throws BusinessException {
		CheckUtils.checkClientResult(result);
		return getResultData(result, null);
	}
	
	public static <T> T getResultData2Error(BaseClientResult<T> result)throws BusinessException {
		return getResultData2Error(result, null);
	}
	
	

	@SuppressWarnings("rawtypes")
	public static BaseClientResult error(Exception e) {
		if (e instanceof BusinessException) {
			BusinessException be = (BusinessException) e;
			return BaseClientResult.error(be.getCode(), be.getMsg());
		} else {
			return BaseClientResult.error();
		}
	}

	@SuppressWarnings("rawtypes")
	public static BaseClientResult error() {
		return error(BaseReturnEnum.SYSTEM_ERROR.getCode(), BaseReturnEnum.SYSTEM_ERROR.getMsg());
	}

	@SuppressWarnings("rawtypes")
	public static BaseClientResult error(String msg) {
		return error(BaseReturnEnum.SYSTEM_ERROR.getCode(), msg);
	}

	@SuppressWarnings("rawtypes")
	public static BaseClientResult error(String code, String msg) {
		BaseClientResult result = new BaseClientResult();
		result.setCode(code);
		result.setMsg(msg);
		return result;
	}

	@SuppressWarnings("rawtypes")
	public static BaseClientResult callbackError() {
		return error(BaseReturnEnum.Remote_Callback_Error.getCode(), BaseReturnEnum.Remote_Callback_Error.getMsg());
	}
	
	
	public static <T> BaseClientResult<T> ok(T data) {
		return BaseClientResult.success(data);
	}
	
	public static <T> BaseClientResult<T> ok() {
		return BaseClientResult.success();
	}
	
	public static <T> BaseClientResult<T> success(T data) {
		BaseClientResult<T> result = new BaseClientResult<T>();
		result.setCode(BaseReturnEnum.SUCCESS.getCode());
		result.setMsg(BaseReturnEnum.SUCCESS.getMsg());
		result.setData(data);
		return result;
	}

	public static <T> BaseClientResult<T> success() {
		BaseClientResult<T> result = new BaseClientResult<T>();
		result.setCode(BaseReturnEnum.SUCCESS.getCode());
		result.setMsg(BaseReturnEnum.SUCCESS.getMsg());
		result.setData(null);
		return result;
	}
	

}
